﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BlueMarble.Genesis.Client.Standard.Forms
{
    public partial class Login : Form, global::Genesis.Common.Interfaces.IDataContainer
    {
        protected System.Data.DataSet globalDataSet;
        protected global::Genesis.Client.Security.Classes.SecurityProvider securityProvider;

        protected DataTable applicationTable;

        public Login(DataSet GlobalDataSet)
        {
            InitializeComponent();

            applicationTable = new DataTable("Active_Application");

            DataColumn applicationGuidColumn = new DataColumn("ApplicationGuid", typeof(Guid));
            DataColumn applicationNameColumn = new DataColumn("ApplicationName", typeof(string));
            DataColumn userGuidColumn = new DataColumn("UserGuid", typeof(Guid));
            DataColumn userNameColumn = new DataColumn("UserName", typeof(string));
            DataColumn subscriberConfigurationIdColumn = new DataColumn("SubscriberConfigurationId", typeof(int));
            DataColumn sourceConfigurationIdColumn = new DataColumn("SourceConfigurationId", typeof(int));
            DataColumn subscriberUserIdColumn = new DataColumn("SubscriberUserId", typeof(int));
            DataColumn sessionGuidColumn = new DataColumn("SessionGuid", typeof(Guid));

            applicationTable.Columns.Add(applicationGuidColumn);
            applicationTable.Columns.Add(applicationNameColumn);
            applicationTable.Columns.Add(userGuidColumn);
            applicationTable.Columns.Add(userNameColumn);
            applicationTable.Columns.Add(subscriberConfigurationIdColumn);
            applicationTable.Columns.Add(sourceConfigurationIdColumn);
            applicationTable.Columns.Add(subscriberUserIdColumn);
            applicationTable.Columns.Add(sessionGuidColumn);

            globalDataSet = GlobalDataSet;
            globalDataSet.Tables.Add(applicationTable);
        }

        #region IDataContainer Members

        public DataSet GlobalDataSet
        {
            get
            {
                return globalDataSet;
            }
            set
            {
                globalDataSet = value;
            }
        }

        public void SaveGlobalDataSet()
        {
            globalDataSet.WriteXml("datastore.xml");
        }

        public void LoadGlobalDataSet()
        {
            globalDataSet.ReadXml("datastore.xml");
        }

        #endregion

        private void buttonSignin_Click(object sender, EventArgs e)
        {
            textBoxUsername.Enabled = false;
            textBoxPassword.Enabled = false;
            comboBoxApplication.Enabled = false;
            buttonCancel.Enabled = false;
            buttonSignin.Enabled = false;

            global::Genesis.Client.Security.Classes.SecurityProvider securityProvider = new global::Genesis.Client.Security.Classes.SecurityProvider();

            Guid sessionGuid = securityProvider.AuthorizeUser(textBoxUsername.Text, textBoxPassword.Text, (Guid)comboBoxApplication.SelectedValue);

            if (sessionGuid != Guid.Empty)
            {
                DataRow newApplicationRow = applicationTable.NewRow();

                newApplicationRow["ApplicationGuid"] = (Guid)((System.Data.DataRowView)comboBoxApplication.SelectedItem)["ApplicationGuid"];
                newApplicationRow["ApplicationName"] = (string)((System.Data.DataRowView)comboBoxApplication.SelectedItem)["ApplicationName"];
                newApplicationRow["UserGuid"] = (Guid)(new global::Genesis.Client.Common.Classes.GenesisProvider().ExecuteScalar("SELECT UserGuid FROM Security_Session WHERE SessionGuid = @SessionGuid ", "GenesisConnectionString", global::Genesis.Client.Common.WebService.Genesis.CommandType.Text, "UserGuidTable", new global::Genesis.Client.Common.WebService.Genesis.DataParameter[] { global::Genesis.Client.Common.Classes.DataParameterFactory.CreateParameter("@SessionGuid", sessionGuid) }));
                newApplicationRow["UserName"] = textBoxUsername.Text;
                newApplicationRow["SessionGuid"] = sessionGuid;

                applicationTable.Rows.Add(newApplicationRow);

                DialogResult = DialogResult.OK;
            }
            else
            {
                textBoxUsername.Enabled = true;
                textBoxPassword.Enabled = true;
                comboBoxApplication.Enabled = true;
                buttonCancel.Enabled = true;
                buttonSignin.Enabled = true;

                textBoxPassword.Text = string.Empty;
                textBoxPassword.Focus();

                MessageBox.Show("Username or password invalid");
            }
        }

        private void comboBox1_Enter(object sender, EventArgs e)
        {
            if (comboBoxApplication.DataSource == null)
            {
                Application.DoEvents();

                textBoxUsername.Enabled = false;
                textBoxPassword.Enabled = false;
                comboBoxApplication.Enabled = false;
                buttonCancel.Enabled = false;
                buttonSignin.Enabled = false;

                global::Genesis.Client.Common.Classes.GenesisProvider genesisProvider = new global::Genesis.Client.Common.Classes.GenesisProvider();

                System.Data.DataTable applicationTable = genesisProvider.ExecuteTable(
                    "select distinct ma.applicationGuid, ma.applicationname from module_application ma inner join security_applicationrole sar on sar.applicationguid = ma.applicationguid inner join security_userrole sur on sur.roleguid = sar.roleguid inner join security_user su on su.userguid = sur.userguid where su.username = @username",
                    "GenesisConnectionString",
                    global::Genesis.Client.Common.WebService.Genesis.CommandType.Text,
                    "ApplicationLookup",
                    global::Genesis.Client.Common.Classes.DataParameterFactory.CreateParameter("@username", textBoxUsername.Text));

                comboBoxApplication.Items.Clear();
                comboBoxApplication.DataSource = applicationTable;
                comboBoxApplication.DisplayMember = "ApplicationName";
                comboBoxApplication.ValueMember = "ApplicationGuid";

                textBoxUsername.Enabled = true;
                textBoxPassword.Enabled = true;
                comboBoxApplication.Enabled = true;
                buttonCancel.Enabled = true;
                buttonSignin.Enabled = true;

                if (comboBoxApplication.Items.Count == 1)
                {
                    buttonSignin.Focus();
                }
                else
                {
                    comboBoxApplication.DroppedDown = true;

                    buttonSignin.Focus();
                }

                Application.DoEvents();
            }
        }

        private void textBoxUsername_TextChanged(object sender, EventArgs e)
        {
            comboBoxApplication.DataSource = null;

            buttonSignin.Enabled = false;

            textBoxPassword.Text = string.Empty;
        }
    }
}
